//
//  YSYSVersion.m
//  YSKitExample
//
//  Created by Kyson on 2017/6/16.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSVersion.h"
#import <StoreKit/StoreKit.h>

@implementation YSAppInfo
- (instancetype)initWithResult:(NSDictionary *)result {
    self = [super init];
    if (!self) return nil;
    self.version                   = result[@"version"];
    self.releaseNotes              = result[@"releaseNotes"];
    self.currentVersionReleaseDate = result[@"currentVersionReleaseDate"];
    self.trackId                   = result[@"trackId"];
    self.bundleId                  = result[@"bundleId"];
    self.trackViewUrl              = result[@"trackViewUrl"];
    self.appDescription            = result[@"appDescription"];
    self.sellerName                = result[@"sellerName"];
    self.fileSizeBytes             = result[@"fileSizeBytes"];
    self.screenshotUrls            = result[@"screenshotUrls"];
    return self;
}
@end

@interface YSVersion () <UIAlertViewDelegate, SKStoreProductViewControllerDelegate>
@property (nonatomic, strong)YSAppInfo *appInfo;
@end

@implementation YSVersion

+ (void)checkNewVersion {
    [[YSVersion sharedVersion] checkNewVersion];
}

+ (void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion {
    [[YSVersion sharedVersion] checkNewVersionAndCustomAlert:newVersion];
}

+ (instancetype)sharedVersion {
    static YSVersion *_v = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _v = [[YSVersion alloc] init];
    });
    return _v;
}

- (void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion{
    [self versionRequest:^(YSAppInfo *appInfo) {
        if(newVersion) newVersion(appInfo);
    }];
}

- (void)checkNewVersion {
    [self versionRequest:^(YSAppInfo *appInfo) {
        NSString *updateMsg = [NSString stringWithFormat:@"%@",appInfo.releaseNotes];
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"发现新版本" message:updateMsg delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
        [alertView show];
#endif
        
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发现新版本" message:updateMsg preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self openInAppStoreForAppURL:self.appInfo.trackViewUrl];
        }]];
        [[self window].rootViewController presentViewController:alert animated:YES completion:nil];
#endif
    }];
}

- (UIWindow *)window{
    UIWindow *window = nil;
    id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate respondsToSelector:@selector(window)]) {
        window = [delegate performSelector:@selector(window)];
    } else {
        window = [[UIApplication sharedApplication] keyWindow];
    }
    return window;
}

#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1) {
        [self openInAppStoreForAppURL:self.appInfo.trackViewUrl];
    }
}
#endif

- (void)openInStoreProductViewControllerForAppId:(NSString *)appId{
    SKStoreProductViewController *storeProductVC = [[SKStoreProductViewController alloc] init];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:appId forKey:SKStoreProductParameterITunesItemIdentifier];
    storeProductVC.delegate = self;
    [storeProductVC loadProductWithParameters:dict completionBlock:^(BOOL result, NSError *error) {
        if (result) {
            [[self window].rootViewController presentViewController:storeProductVC animated:YES completion:nil];
        }
    }];
}

- (void)openInAppStoreForAppURL:(NSString *)appURL{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]];
}

- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)versionRequest:(NewVersionBlock)newVersion {
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *bundleId = infoDict[@"CFBundleIdentifier"];
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@",bundleId]];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(!error) {
                    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                    NSInteger resultCount = [responseDict[@"resultCount"] integerValue];
                    if(resultCount == 1) {
                        NSArray *resultArray = responseDict[@"results"];
                        NSDictionary *result = resultArray.firstObject;
                        YSAppInfo *appInfo = [[YSAppInfo alloc] initWithResult:result];
                        NSString *version = appInfo.version;
                        self.appInfo = appInfo;
                        if([self isNewVersion:version]) {
                            if(newVersion) newVersion(self.appInfo);
                        }
                    }
                } else {
                    NSLog(@"网络连接失败");
                }
            });
        }];
        [dataTask resume];
    });
}

- (BOOL)isNewVersion:(NSString *)newVersion {
    if([[self currentVersion] compare:newVersion options:NSNumericSearch] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}

- (NSString * )currentVersion{
    NSString *key = @"CFBundleShortVersionString";
    NSString * currentVersion = [NSBundle mainBundle].infoDictionary[key];
    return currentVersion;
}

@end
